package com.zhava.crawler.infrastructure.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVWriter;
import com.zhava.crawler.domain.enums.OutputFormatEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 文件导出工具类
 *
 * @author zhaxiang
 */
public class FileExportUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileExportUtil.class);
    private static final String BASE_DIR = "file";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 导出数据到文件
     *
     * @param data 要导出的数据
     * @param format 输出格式
     * @param filePrefix 文件名前缀
     * @return 导出的文件路径，如果导出失败则返回null
     */
    public static String exportToFile(Object data, OutputFormatEnum format, String filePrefix) {
        try {
            // 创建目录
            createDirIfNotExists();
            
            // 生成文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = String.format("%s_%s.%s", filePrefix, timestamp, getFileExtension(format));
            String filePath = Paths.get(BASE_DIR, fileName).toString();
            
            // 根据格式导出数据
            switch (format) {
                case JSON:
                    return exportAsJson(data, filePath);
                case CSV:
                    return exportAsCsv(data, filePath);
                case RAW:
                default:
                    return exportAsText(data, filePath);
            }
        } catch (Exception e) {
            logger.error("导出文件失败", e);
            return null;
        }
    }
    
    /**
     * 创建文件目录（如果不存在）
     */
    private static void createDirIfNotExists() throws IOException {
        Path path = Paths.get(BASE_DIR);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
    }
    
    /**
     * 根据输出格式获取文件扩展名
     */
    private static String getFileExtension(OutputFormatEnum format) {
        switch (format) {
            case JSON:
                return "json";
            case CSV:
                return "csv";
            case RAW:
            default:
                return "txt";
        }
    }
    
    /**
     * 将数据导出为JSON文件
     */
    private static String exportAsJson(Object data, String filePath) throws IOException {
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(filePath), data);
        return filePath;
    }
    
    /**
     * 将数据导出为CSV文件
     */
    private static String exportAsCsv(Object data, String filePath) throws IOException {
        try (CSVWriter writer = new CSVWriter(new FileWriter(filePath))) {
            if (data instanceof List) {
                List<?> list = (List<?>) data;
                for (Object item : list) {
                    writer.writeNext(new String[]{item.toString()});
                }
            } else {
                writer.writeNext(new String[]{data.toString()});
            }
        }
        return filePath;
    }
    
    /**
     * 将数据导出为文本文件
     */
    private static String exportAsText(Object data, String filePath) throws IOException {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(data.toString());
        }
        return filePath;
    }
} 